package cn.wp.user.interceptor;

import cn.wp.user.domain.LoginInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * 登录拦截器
 */
@Component
public class LoginInterceptor implements HandlerInterceptor{

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        // 获取请求头信息
        String token = request.getHeader("TOKEN");
        if (StringUtils.isEmpty(token)){
            writeJson(response);
            return false;
        }

        LoginInfo info = (LoginInfo) redisTemplate.opsForValue().get(token);
        if (info == null){
            writeJson(response);
            return false;
        }

        // 如果有就再将登录信息放入redis
        redisTemplate.opsForValue().set(token, info,30, TimeUnit.MINUTES);

        return true;
    }

    private void writeJson(HttpServletResponse response) throws IOException {
        response.setContentType("text/json;charset=utf-8");
        response.getWriter().write("{\"success\":false,\"msg\":\"NoLogin\"}");

    }
}
